package com.itheima.controller;

/**
 * @author Dugen.Zhu
 * @date 2019-12-29 11:16
 */

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@Controller
@RequestMapping("/orderMobile")
public class OrderMobileController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @RequestMapping("/submitOrder")
    @ResponseBody
    public Result submitOrder(@RequestBody Map orderInfo) {
        //获取验证码，校验用户输入的验证码是否正确
        String validateCode_user = (String) orderInfo.get("validateCode");
        String telephone_user = (String) orderInfo.get("telephone");
        String code = jedisPool.getResource().get(telephone_user + RedisMessageConstant.SENDTYPE_ORDER);
        if (!(validateCode_user != null && telephone_user != null && validateCode_user.length() > 0 && telephone_user.length() > 0)) {
            //手机号和验证码都为空
            return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        if (code == null) {
            //验证码已过期，为了方便测试，我设置了过期时间是60秒
            return new Result(false, MessageConstant.VALIDATECODE_EXPIRED);
        }
        if (!validateCode_user.equals(code)) {
            //验证码不正确
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //调用service预约
        Result orderResult = null;
        try {
            orderInfo.put("orderType", Order.ORDERTYPE_WEIXIN);
            orderResult = orderService.order(orderInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //预约成功,给用户发送预约成功短信,因为阿里云权限问题，不给发送通知短信
        /*if (orderResult.isFlag()) {
            String orderDate = (String) orderInfo.get("orderDate");
            try {
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone_user, orderDate);
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }*/
        return orderResult;
    }

    @RequestMapping("/findById")
    @ResponseBody
    public Result findById(Integer id) {
        try {
            Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }

    }

}
